import 'package:flutter/material.dart';
import 'package:flutterapp900sui/models/listModelItems.dart';
import 'package:flutterapp900sui/models/networking.dart';
import 'package:flutterapp900sui/models/networkApiList.dart';

import 'package:flutterapp900sui/views/businessListItemCell.dart';
import 'package:flutterapp900sui/controllers/businessDetailPageController.dart';

class HomePageWidget extends StatefulWidget {
  HomePageWidget({Key key}) : super(key: key);

  @override
  _HomePageWidgetState createState() => _HomePageWidgetState();
}

class _HomePageWidgetState extends State<HomePageWidget> {

  bool isLogin = true;
  //  分类
  Set<ListCellItem> _categoryItems = Set<ListCellItem>();
  //  精选推荐的服务
  List<ListCellItem> _recommendedServiceItems = List<ListCellItem>();
  //  推荐的商家
  List<ListCellItem> _recommendedBusinessItems = List<ListCellItem>();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    Networking.get(RequestListApi.api_getCategoryList).then((value){
      List itemList = value['data'];
      if(itemList.isNotEmpty){
        _categoryItems.clear();
        itemList.forEach((element) {
          var cellItem = ListCellItem(element['IndustryName']);
          cellItem.key = element['IndustryId'].toString();
          cellItem.icon = Image.network(element['IndustryIconUrl'],width: 30,height: 30,);
          _categoryItems.add(cellItem);
        });

        var cellItem = ListCellItem('全部');
        cellItem.icon = Image.asset('images/home_category_item_all.png',width: 30,height: 30,);
        _categoryItems.add(cellItem);
      }
      setState(() {});
    });
    
    Networking.get(RequestListApi.api_getSelectServices,parameters: {"num":"3"}).then((value){
      print('精选服务:${value}');
      List itemList = value['data'];
      if(itemList.isNotEmpty){
        _recommendedServiceItems.clear();
        itemList.forEach((element) {
          var cellItem = ListCellItem('');
          cellItem.anyObject = element;
          _recommendedServiceItems.add(cellItem);
        });
      }
      setState(() {});
    });
    
    Networking.get(RequestListApi.api_getShopList,parameters: {"pageSize":"20"}).then((value){
      print('推荐的商家:${value}');
      Map itemJson = value['data'];
      List itemList = itemJson['Lists'];
      if(itemList.isNotEmpty){
        _recommendedBusinessItems.clear();
        itemList.forEach((element) {
          var cellItem = ListCellItem('');
          cellItem.anyObject = element;
          _recommendedBusinessItems.add(cellItem);
        });
      }
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context){
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.red,
      ),
      body: ListView.builder(itemBuilder: (BuildContext context, int index){
        if(index == 0){
          return _buildTopHeaderWidget();
        }else if(index == 1){
          return _buildTopFunctionWidget();
        }else if(index == 2){
          return _buildBannerAndInformation();
        }else if(index == 3){
          return _buildCategoryWidget();
        }else if(index == 4){
          return _buildRecommendedServiceWidget();
        }else if(index == 5){
          return _buildRecommendedBusinessHeaderWidget();
        }else{
          return Container(
            height: 130,
            alignment: Alignment.topCenter,
            child: BusinessListItemCell(handleBlock: (int selected){
              print("回调的参数为$index");
              Navigator.push(context, MaterialPageRoute(builder: (_){
                return new BusinessDetailPageWidget();
              }));
            },cellItem: _recommendedBusinessItems[index - 6],),
          );
        }
      },itemCount: _recommendedBusinessItems.length + 6,)
    );
  }

  //  UI创建
  //  顶部数据显示的Widget
  Widget _buildTopHeaderWidget(){
    return Container(
      child: ClipRRect(
        borderRadius: BorderRadius.only(bottomLeft: Radius.circular(50),bottomRight: Radius.circular(50)),
        child: Container(
          height: 240,
          color: Colors.red,
          child: Container(
            margin: EdgeInsets.only(left: 10,top: 20,right: 10),
            child: ClipRRect(
              borderRadius: BorderRadius.only(topLeft: Radius.circular(10),topRight: Radius.circular(10)),
              child: Container(
                child: Stack(
                  children: [
                    Positioned(
                      left: 0,
                      right: 0,
                      child: Image.asset('images/home_topCell_bg.png'),
                    ),
                    Column(
                      children: [
                        Expanded(
                            child: Stack(
                              children: [
                                Positioned(
                                    right:10,
                                    top: 20,
                                    width: 40,
                                    height: 40,
                                    child: Image.asset('images/home_state_green.png')
                                ),
                                Positioned(
                                    left: 0,
                                    right: 0,
                                    height: 160,
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Container(
                                          height: 50,
                                          padding: EdgeInsets.only(left: 20,top: 20),
                                          child: Text('您的预付消费卡累计可消费金额为',style: TextStyle(
                                              color: Colors.white,
                                              fontSize: 14.0
                                          )),),
                                        Expanded(
                                          child: Container(
                                            margin: EdgeInsets.all(5),
                                            alignment: Alignment.topCenter,
                                            child: isLogin ?
                                            Container(
                                              margin: EdgeInsets.only(top: 10),
                                              height: 40,
                                              width: 40,
                                              alignment: Alignment.center,
                                              child: Row(
                                                children: [
                                                  Text('¥ ',style: TextStyle(
                                                      color: Colors.orange,
                                                      fontSize: 12.0
                                                  )),
                                                  Text('0',style: TextStyle(
                                                      color: Colors.orange,
                                                      fontSize: 20.0
                                                  )),
                                                ],
                                              ),
                                            ) :
                                            Container(
                                              margin: EdgeInsets.only(top: 10),
                                              width: 100,
                                              height: 40,
                                              alignment: Alignment.center,
                                              decoration: BoxDecoration(
                                                borderRadius: BorderRadius.all(Radius.circular(5.0)),
                                                border: Border.all(width: 1, color: Colors.white),
                                              ),
                                              child: Text("登录后查看",style: TextStyle(
                                                  color: Colors.white,
                                                  fontSize: 14.0
                                              ),),
                                            ),
                                          ),
                                        )
                                      ],
                                    ))
                              ],
                            )
                        ),
                        Container(
                          height: 100,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              _buildTopHeaderWidgetSubCell("预付卡", "**"),
                              _buildTopHeaderWidgetSubCell("预约中", "**"),
                              _buildTopHeaderWidgetSubCell("红包/券", "**"),
                              _buildTopHeaderWidgetSubCell("积分", "**")
                            ],
                          ),
                        )
                      ],
                    ),
                  ],
                )
              ),
            ),
          ),
        ),
      )
    );
  }

  Widget _buildTopHeaderWidgetSubCell(String title, String value){

    return Container(
      width: 100,
      child: Container(
        margin: EdgeInsets.only(top: 10),
        height: 50,
        child: Column(
          children: [
            Container(
              height: 25,
              child: Text(
                "$title",
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 14.0
                ),),),
            Container(
              height: 25,
              child: Text(
                "$value",
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 13.0
                ),
              ),),
          ],
        ),
      )
    );
  }

  //  首页功能Widget
  Widget _buildTopFunctionWidget(){
    return Container(
      margin: EdgeInsets.only(left: 10,right: 10),
      height: 100,
      child: GridView(
        physics: new NeverScrollableScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4,
          childAspectRatio: 1.0
        ),
        children: [
          _buildTopFunctionWidgetSubCell(Color(0XFF05C886), 'images/icon_main_cardManager.png', '卡包管理'),
          _buildTopFunctionWidgetSubCell(Color(0XFFFFA533), 'images/icon_main_message.png', '消息中心'),
          _buildTopFunctionWidgetSubCell(Color(0XFF008FFE), 'images/icon_main_book.png', '预约管理'),
          _buildTopFunctionWidgetSubCell(Color(0XFFFF4E60), 'images/icon_main_cardSearch.png', '卡查查')
        ],
      ),
    );
  }

  Widget _buildTopFunctionWidgetSubCell(Color bgColor,String iconName, String title){
    return Container(
      alignment: Alignment.topCenter,
      width: 100,
      margin: EdgeInsets.only(top: 10),
      child: Column(
        children: [
          Container(
            height: 70,
            width: 80,
            alignment: Alignment.center,
            child: Stack(
              children: [
                Container(
                  height: 50,
                  width: 50,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(15.0)),
                    color: bgColor,
                ),
              ),
              Positioned(
                left: 10,
                  top: 10,
                  child: Container(
                    width: 30,
                    height: 30,
                    child: Image.asset(iconName),
                  )
              ),
            ],
          ),
          ),
          Text(title)
        ],
      ),
    );
  }

  //  首页轮播图+资讯信息
  Widget _buildBannerAndInformation(){
    return Container(
      margin: EdgeInsets.all(10),
      height: 160,
      child: ClipRRect(
        borderRadius:  BorderRadius.all(Radius.circular(10.0)),
        child: Container(
          color: Colors.white,
          child: Column(
            children: [
              Expanded(child: Container(color: Colors.blue,)),
              Container(
                height: 44,
                child: Row(
                  children: [
                    Container(
                      margin: EdgeInsets.only(right: 10),
                      width: 80,
                      child: Image.asset('images/home_newsCell_tips.png'),
                    ),
                    Expanded(child:
                      Container(
                        child: Text('突如其来的被"跑路"学霸君创造突如其来的被"跑路"学霸君创造',softWrap: false,overflow: TextOverflow.ellipsis,),
                      ),
                    ),
                    Container(
                      width: 60,
                      alignment: Alignment.center,
                      child: GestureDetector(
                        onTap: (){},
                        child: Text('更多'),
                      ),),
                  ],
                ),
              )
            ],
          ),
        ),
      )
    );
  }

  //  首页分类Widget
  Widget _buildCategoryWidget(){

    var categoryItemCells = _categoryItems.map((e) {
      return _buildCategoryCellWidget(e.title, e.icon);
    }).toList();

    return Container(
        margin: EdgeInsets.all(10),
        height: 214,
        child: ClipRRect(
          borderRadius:  BorderRadius.all(Radius.circular(10.0)),
          child: Container(
            color: Colors.white,
            child: Column(
              children: [
                Container(
                  height: 44,
                  child: Row(
                    children: [
                      Container(
                        margin: EdgeInsets.only(right: 10),
                        width: 30,
                        child: Container(
                          width: 20,
                          height: 14,
                          color: Colors.red,
                        )
                      ),
                      Container(
                        width: 100,
                        child: Text('放心买卡'),
                      ),
                      Expanded(child:
                        Container(
                          child: Image.asset('images/home_section_top_right.png'),
                        )
                      ),
                    ],
                  ),
                ),
                Expanded(child:
                  Container(
                    child: GridView(
                      physics: new NeverScrollableScrollPhysics(),
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 5,
                          childAspectRatio: 1.0,
                          crossAxisSpacing: 5,
                          mainAxisSpacing:5
                      ),
                      children: categoryItemCells
                    )
                  )
                )
              ],
            ),
          ),
        )
    );
  }

  Widget _buildCategoryCellWidget(String title, Image icon){
    return Container(
      child: Column(
        children: [
          Container(
            margin: EdgeInsets.only(top: 10,bottom: 5),
            width: 30,
            height: 30,
            child: icon,
          ),
          Text(title, style: TextStyle(fontSize: 12.0),),
        ],
      ),
    );
  }

  //  首页精选服务Widget
  Widget _buildRecommendedServiceWidget(){

    List<Widget> serviceCellItems = [];

    _recommendedServiceItems.forEach((element) {
      serviceCellItems.add(_buildRecommendedCellWidget(element.anyObject));
    });

    return Container(
        margin: EdgeInsets.all(10),
        height: 344,
        child: ClipRRect(
          borderRadius:  BorderRadius.all(Radius.circular(10.0)),
          child: Container(
            color: Colors.white,
            child: Column(
              children: [
                Container(
                  height: 44,
                  child: Row(
                    children: [
                      Container(
                          margin: EdgeInsets.only(right: 10),
                          width: 30,
                          child: Container(
                            width: 20,
                            height: 14,
                            color: Colors.red,
                          )
                      ),
                      Container(
                        width: 100,
                        child: Text('精选服务'),
                      ),
                      Expanded(child:
                      Container(
                        child: Image.asset('images/home_section_top_right.png'),
                      )
                      ),
                    ],
                  ),
                ),
                Expanded(child:
                  Column(
                    children: serviceCellItems
                  )
                )
              ],
            ),
          ),
        )
    );
  }

  Widget _buildRecommendedCellWidget(Map item){

    var singleName = item['SingleName'];
    var realPricce = item['RealPrice'];
    var sales = item['Sales'];
    var iconPath = item['ImgPath'];

    return Container(
      height: 100,
      child: Row(
        children: [
          Container(
            margin: EdgeInsets.only(left: 10),
            alignment: Alignment.centerLeft,
            width: 100,
            height: 75,
            child: ClipRRect(
              borderRadius:  BorderRadius.all(Radius.circular(5)),
              child: Container(
                color: Colors.orange,
                child: Image(image: NetworkImage(iconPath),width: 100,height: 75,fit: BoxFit.cover),
              ),
            ),
          ),
          Expanded(
            child: Container(
                padding: EdgeInsets.all(10),
                alignment: Alignment.topLeft,
                child: Column(
                  children: [
                    Container(margin: EdgeInsets.only(top: 3), alignment: Alignment.centerLeft, child: Text(singleName),),
                    Expanded(child: Container(alignment: Alignment.centerLeft, child: Text('¥${realPricce}',style: TextStyle(color: Colors.red),),)),
                    Container(margin: EdgeInsets.only(bottom: 3), alignment: Alignment.centerLeft, child: Text('已售${sales}'),)
                  ],
                )
            ),
          )
        ],
      ),
    );
  }

  //  首页为您推荐
  Widget _buildRecommendedBusinessHeaderWidget(){

    var lineColor = Color(0XFFFED2D5);

    return Container(
      height: 40,
      child: Stack(
        children: [
          Positioned(
              left: 0,
              right: 0,
              top: 10,
              height: 20,
              child: Container(
                child: Row(
                  children: [
                    Expanded(child: Container(height: 1,color: lineColor,margin: EdgeInsets.only(left: 30),)),
                    Container(width: 100,height: 16,decoration: BoxDecoration(
                        borderRadius:  BorderRadius.all(Radius.circular(8.0)),
                        color: lineColor
                      ),
                    ),
                    Expanded(child: Container(height: 1,color: lineColor,margin: EdgeInsets.only(right: 30),))
              ],
            ),
          )),
          Positioned(
              left: 30,
              right: 30,
              top: 5,
              child: Container(
                alignment: Alignment.center,
                child: Text('为您推荐', style: TextStyle(fontSize: 17,color: Colors.red),),
          ))
        ],
      ),
    );
  }
}